import React, {useEffect,useState} from 'react';
import {Button, Checkbox, Form, Input, message, Modal, TreeSelect,Skeleton } from "antd";
import {getRoles, getUserDetail, updateUser} from "@/services/people";
import {getSections} from "@/services/section";

const Edit = (props) => {
  const {treeData,isModalDisplay,editModalIsShow,userinfo,actionRef,editId}=props
  const { TreeNode } = TreeSelect;
  const [allRoles,setRoles]=useState([]);
  const [sections,setSections]=useState([]);
  const [userInfoInitValues,setUserInfoInitValues]=useState(undefined)
  /**
   * 通过id获取用户的数据
   */
  useEffect(async ()=>{
    // 获取角色和部门的列表
    let sectionList=await getSections();
    setSections(sectionList.data);
    // 获取角色列表
    let rolelist = await getRoles();
    setRoles(rolelist.data);
    // 发送请求获取用户的详情
    if(editId !==undefined){
      let response=await getUserDetail(editId);
      console.log(response)
      setUserInfoInitValues({
        id:editId,
        name:response.info.name,
        username:response.info.username,
        id_card:response.info.id_card,
        email:response.info.email,
        phone:response.info.phone,
        status:response.status,
        section:response.info.section.map((item)=>{
          return item.id;
        }),
        roles:response.info.roles.map((item)=>{
          return item.id;
        })
      })
    }
  },[])


  /**
   * 编辑的表单提交
   * @param params
   * @returns {Promise<{pagination: *, data: *, message: string}>}
   */
  const editUserSubmit=async (value)=>{
    console.log(value)
    //执行修改的api
    let updateRes=await updateUser(value);
    console.log(updateRes)
    // 这里进行结果的判断
    if(updateRes.status === undefined){
      message.success('修改成功');
      actionRef.current.reload();
      editModalIsShow(false);
    }
  }
  /**
   * treeselect的事件
   */
  const onChange = () => {
  };

  return (
    <Modal
      destroyOnClose={true}
      title="编辑用户"
      visible={isModalDisplay}
      onCancel={()=>{editModalIsShow(false)}}
      footer={null}
    >
      {
        userInfoInitValues === undefined
          ?
          <Skeleton active />
          :
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
            labelAlign={'right'}
            initialValues={userInfoInitValues}   name="control-ref" onFinish={values=>editUserSubmit(values)}>
            <Form.Item name="username" label="登录名" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="name" label="用户名" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item name="email" label="邮箱" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label="手机号"
              rules={
                [
                  {
                    required: true ,
                    message:'手机号必填'
                  },
                  {
                    pattern: /^1\d{10}$/ ,
                    message:'手机号格式不合法'
                  }
                ]
              }>
              <Input />
            </Form.Item>
            <Form.Item name="id_card" label="身份证" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item
              name="section"
              label="部门"
              rules={
                [
                  {
                    required: true ,
                    message:'部门必填'
                  }
                ]
              }>
              <TreeSelect
                multiple={true}
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择部门"
                allowClear
                treeDefaultExpandAll
                onChange={onChange}
              >
                {sections.map((item)=>{
                  return (
                    <TreeNode  key={item.id} value={item.id} title={item.name}>
                      {item.children && item.children.map((items)=>{
                        return (
                          <TreeNode  key={items.id} value={items.id} title={items.name}>
                            {items.children ? items.children.map((itembottom)=>{
                              return (<TreeNode value={itembottom.id} key={itembottom.id} title={itembottom.name} />)
                            }) : ''}

                          </TreeNode>
                        )
                      })}
                    </TreeNode>
                  )
                })}
              </TreeSelect>
            </Form.Item>
            <Form.Item name="roles" label="角色" rules={[{ required: true }]} >
              {allRoles.map((item)=>{
                return (<Checkbox
                  key={item.id}
                  value={item.id}
                  checked={
                    userinfo.roles ?
                      (userinfo.roles.indexOf(item.id) === -1 ? false : true)
                      : ''
                  }
                  style={{ lineHeight: '32px' }}>
                  {item.cn_name}
                </Checkbox>)
              })}
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" >
                提交
              </Button>
              <Button htmlType="button">
                重置
              </Button>
            </Form.Item>
          </Form>
      }
    </Modal>
  );
};

export default Edit;
